<script lang="ts" setup>
import { ref, reactive, watch } from "vue"
import { CirclePlus, Search, Refresh, Download } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { type FormInstance, type FormRules, type TabsPaneContext, ElMessage } from "element-plus"

import { getTeamDataApi } from "@/api/team"
import { formatDateTime } from "@/utils"
import { checkID, checkPhoneNumber } from "@/utils/validate"
import {
  getRiskControlCenterApi,
  addRiskControlCenterApi,
  updateRiskControlCenterApi,
  downLoaRiskTable
} from "@/api/RiskControlCenter"
import { shortcuts } from "@/utils/dateSet"
import { useUserStore } from "@/store/modules/user" // 用户信息
defineOptions({
  name: "FkUser"
})
const userStore = useUserStore() // 用户信息
const activeName = ref("one")
const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const formRef = ref<FormInstance | null>(null)
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive<any>({
  id: "", // 身份证号
  time: "", // 时间
  risk_level: "0", // 状态区分用户
  risk_name: "", // 联系人姓名
  risk_phone: "", // 联系人电话
  risk_card_name: "" // 身份证姓名
})

// #region 高危用户添加弹出框和高危用户查看
const dialogVisible = ref<boolean>(false)
const tableData = ref<any>([])
const tableDataTotal = ref<any>(0)
const getRiskControlCenter = () => {
  if (!searchData.time) {
    searchData.time = []
  }
  getRiskControlCenterApi({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    start: new Date(searchData.time[0]).getTime() || "",
    end: new Date(searchData.time[1]).getTime() || "",
    id: searchData.id || "",
    risk_level: searchData.risk_level,
    risk_name: searchData.risk_name,
    risk_phone: searchData.risk_phone,
    risk_card_name: searchData.risk_card_name
  }).then((res: any) => {
    tableDataTotal.value = res.data.total
    tableData.value = res.data.riskList
  })
}
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getRiskControlCenter, { immediate: true })
// 获取团队
const TeamListArr = ref()
const getAddTeam = () => {
  getTeamDataApi({
    page: 1,
    size: 1000000
  }).then((res: any) => {
    TeamListArr.value = res.data.teamList
    // console.log("--团队名", TeamListArr.value)
  })
}
getAddTeam()
// #endregion

// #region 搜索功能
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getRiskControlCenter()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getRiskControlCenter()
  }
  paginationData.currentPage = 1
}
// #endregion

// #region 改
const currentUpdateId = ref<undefined | string>(undefined)
const formData = reactive<any>({
  risk_id: "",
  risk_order_id: "",
  risk_team: "",
  risk_wang: "",
  risk_hao: "",
  risk_name: "",
  risk_phone: "",
  risk_address: "",
  risk_card_name: "",
  risk_card_id: "",
  risk_level: "",
  risk_tip: ""
})
const handleUpdate = (row: any) => {
  currentUpdateId.value = row.risk_id
  formData.risk_order_id = row.risk_order_id
  formData.risk_team = row.risk_team
  formData.risk_wang = row.risk_wang
  formData.risk_hao = row.risk_hao
  formData.risk_name = row.risk_name
  formData.risk_phone = row.risk_phone
  formData.risk_address = row.risk_address
  formData.risk_card_name = row.risk_card_name
  formData.risk_card_id = row.risk_card_id
  formData.risk_tip = row.risk_tip
  dialogVisible.value = true
  console.log(row, "修改")
  console.log(currentUpdateId.value, "修改")
}
// #endregion

// #region 增改弹出框验证
const formRules: FormRules = reactive({
  // risk_order_id: [{ required: true, trigger: "blur", message: "请输入订单编号" }],
  // risk_team: [{ required: true, trigger: "change", message: "请选择团队" }],
  // risk_name: [{ required: true, trigger: "blur", message: "请输入联系人姓名" }],
  // // risk_hao: [{ required: true, trigger: "blur", message: "请输入旺旺号" }],
  // risk_phone: [
  //   { required: true, trigger: "blur", message: "请输入联系人电话" },
  //   { required: true, validator: checkPhoneNumber, trigger: "blur" }
  // ],
  // risk_address: [{ required: true, trigger: "blur", message: "请输入地址" }],
  // risk_card_name: [{ required: true, trigger: "blur", message: "请输入身份证姓名" }],
  // risk_card_id: [
  //   { required: true, trigger: "blur", message: "请输入身份证号" },
  //   { required: true, validator: checkID, trigger: "blur" }
  // ],
  // risk_level: [{ required: true, trigger: "change", message: "请选择风险类型" }],
  // risk_tip: [{ required: true, trigger: "blur", message: "请输入原因" }]
})
const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (currentUpdateId.value === undefined) {
        addRiskControlCenterApi({
          risk_order_id: formData.risk_order_id,
          risk_team: formData.risk_team,
          risk_wang: formData.risk_wang,
          risk_hao: formData.risk_hao,
          risk_name: formData.risk_name,
          risk_phone: formData.risk_phone,
          risk_address: formData.risk_address,
          risk_card_name: formData.risk_card_name,
          risk_card_id: formData.risk_card_id,
          risk_level: formData.risk_level,
          risk_tip: formData.risk_tip
        }).then(() => {
          ElMessage.success("新增成功")
          dialogVisible.value = false
          getRiskControlCenter()
        })
      } else {
        updateRiskControlCenterApi({
          risk_id: currentUpdateId.value,
          risk_order_id: formData.risk_order_id,
          risk_team: formData.risk_team,
          risk_wang: formData.risk_wang,
          risk_hao: formData.risk_hao,
          risk_name: formData.risk_name,
          risk_phone: formData.risk_phone,
          risk_address: formData.risk_address,
          risk_card_name: formData.risk_card_name,
          risk_card_id: formData.risk_card_id,
          risk_level: formData.risk_level,
          risk_tip: formData.risk_tip
        }).then(() => {
          ElMessage.success("修改成功")
          dialogVisible.value = false
          getRiskControlCenter()
        })
      }
    } else {
      return false
    }
  })
}
// ** 清除规则报错信息
const clearValidate = () => {
  formRef.value?.resetFields()
}
const resetForm = () => {
  currentUpdateId.value = undefined
  clearValidate()
  // 清空reactive对象里面的key值
  Object.keys(formData).map((key) => {
    delete formData[key]
  })
}
// #endregion

// 区分中低危用户数据展示
const handleClick = (tab: TabsPaneContext) => {
  paginationData.currentPage = 1
  // console.log(tab.paneName)
  if (tab.paneName == "one") {
    searchData.risk_level = "0"
  }
  if (tab.paneName == "two") {
    searchData.risk_level = "1"
  }
  if (tab.paneName == "stree") {
    searchData.risk_level = "2"
  }
  getRiskControlCenter()
}

//导出高危用户
const downLoad = () => {
  loading.value = true
  downLoaRiskTable({})
    .then((res: any) => {
      if (res.data.code === 500) {
        ElMessage.error(res.data.message)
        return false
      }
      const blob = new Blob([res.data], {
        type: "application/xlsx;charset=utf-8"
      })
      // console.log(res)
      const downloadElement = document.createElement("a")
      const href = window.URL.createObjectURL(blob)
      downloadElement.href = href
      downloadElement.download = "高危用户.xlsx"
      document.body.appendChild(downloadElement)
      downloadElement.click()
      window.URL.revokeObjectURL(href)
      // }
    })
    .finally(() => {
      loading.value = false
    })
}

//时间
const defaultTime1: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 0)]
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <div class="toolbar-wrapper">
        <div>
          <el-form ref="searchFormRef" :inline="true" :model="searchData">
            <el-form-item prop="time" label="订单日期">
              <el-date-picker
                v-model="searchData.time"
                type="datetimerange"
                range-separator="到"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :shortcuts="shortcuts"
                :default-time="defaultTime1"
              />
            </el-form-item>
            <el-form-item prop="id" label="身份证号">
              <el-input v-model.trim="searchData.id" placeholder="请输入" />
            </el-form-item>
            <el-form-item prop="risk_name" label="联系人姓名">
              <el-input v-model.trim="searchData.risk_name" placeholder="请输入" />
            </el-form-item>
            <el-form-item prop="risk_phone" label="联系人电话">
              <el-input v-model.trim="searchData.risk_phone" placeholder="请输入" />
            </el-form-item>
            <el-form-item prop="risk_card_name" label="身份证姓名">
              <el-input v-model.trim="searchData.risk_card_name" placeholder="请输入" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
              <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
          <el-button
            type="primary"
            v-if="userStore.roles[0] == '超级管理员' || userStore.roles[0] == '管理账户'"
            :icon="CirclePlus"
            @click="dialogVisible = true"
            >添加用户</el-button
          >
        </div>
        <div>
          <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle @click="downLoad" />
          </el-tooltip>
        </div>
      </div>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="table-wrapper">
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="高危用户" name="one" />
          <el-tab-pane label="中危用户" name="two" />
          <el-tab-pane label="低危用户" name="stree" />
        </el-tabs>
        <el-table :data="tableData">
          <el-table-column prop="risk_time" label="日期" align="center" width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.risk_time) }}
            </template>
          </el-table-column>
          <el-table-column prop="risk_order_id" label="第三方订单编号" align="center" />
          <el-table-column prop="risk_team" label="归属地店铺" align="center" />
          <el-table-column prop="risk_wang" label="旺旺名" align="center" />
          <!-- <el-table-column prop="risk_hao" label="旺旺号" align="center" /> -->
          <el-table-column prop="risk_name" label="联系人姓名" align="center" />
          <el-table-column prop="risk_phone" label="联系人电话" align="center" />
          <el-table-column prop="risk_address" label="地址" align="center" />
          <el-table-column prop="risk_card_name" label="身份证姓名" align="center" />
          <el-table-column prop="risk_card_id" label="身份证号" align="center" />
          <el-table-column label="风险类型" align="center">
            <template #default="scope">
              <div v-if="scope.row.risk_level == '0'">高危用户</div>
              <div v-if="scope.row.risk_level == '1'">中危用户</div>
              <div v-if="scope.row.risk_level == '2'">低危用户</div>
            </template>
          </el-table-column>
          <el-table-column prop="risk_tip" label="情况说明" align="center" />
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="tableDataTotal"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentUpdateId === undefined ? '新增用户风险' : '修改用户风险'"
      @close="resetForm"
      width="30%"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="risk_order_id" label="订单编号">
          <el-input v-model="formData.risk_order_id" placeholder="请输入第三方订单编号" />
        </el-form-item>
        <el-form-item prop="risk_team" label="归属团队">
          <el-select v-model="formData.risk_team" clearable placeholder="请选择归属团队">
            <el-option v-for="item in TeamListArr" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <!-- 非必填 -->
        <el-form-item prop="risk_wang" label="旺旺名">
          <el-input v-model="formData.risk_wang" placeholder="请输入旺旺名" />
        </el-form-item>
        <!-- <el-form-item prop="risk_hao" label="旺旺号">
          <el-input v-model="formData.risk_hao" placeholder="请输入旺旺号" />
        </el-form-item> -->
        <el-form-item prop="risk_name" label="联系人姓名">
          <el-input v-model="formData.risk_name" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item prop="risk_phone" label="联系人电话">
          <el-input v-model="formData.risk_phone" placeholder="请输入联系人电话" />
        </el-form-item>
        <el-form-item prop="risk_address" label="地址">
          <el-input v-model="formData.risk_address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item prop="risk_card_name" label="身份证姓名">
          <el-input v-model="formData.risk_card_name" placeholder="请输入身份证姓名" />
        </el-form-item>
        <el-form-item prop="risk_card_id" label="身份证号">
          <el-input v-model="formData.risk_card_id" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item prop="risk_level" label="风险类型">
          <el-select v-model="formData.risk_level" clearable placeholder="请选择风险类型">
            <el-option label="高危用户" value="0" />
            <el-option label="中危用户" value="1" />
            <el-option label="低危用户" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item prop="risk_tip" label="原因">
          <el-input v-model="formData.risk_tip" type="textarea" placeholder="请输入原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
